package com.cloud.tsp.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.api.domain.tsp.QueryTenant;
import com.cloud.api.domain.tsp.VehicleTenant;
import com.cloud.api.myenum.LeaseCycleEnum;
import com.cloud.mybatis.domain.TableDataInfo;
import com.cloud.tsp.mapper.VehicleTenantMapper;
import com.cloud.tsp.service.IVehicleTenantService;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author haohaibo
 * @since 2023-11-27
 */
@Service("vehicleTenantService")
public class VehicleTenantServiceImpl extends ServiceImpl<VehicleTenantMapper, VehicleTenant> implements IVehicleTenantService {

    @Resource
    private VehicleTenantMapper vehicleTenantMapper;
    @Resource
    private MessageSource messageSource;

    @Override
    public TableDataInfo<VehicleTenant> selectTenantList(QueryTenant para) {
        Page<VehicleTenant> page =new Page<>();
        page.setCurrent(para.getPage());
        page.setSize(para.getPageSize());
        IPage<VehicleTenant> data = vehicleTenantMapper.selectTenantList(page, para);
        /*if (data.getTotal()>0){
            data.getRecords().stream().forEach(a -> a.setTransLeaseCycle(LeaseCycleEnum.getInstance(a.getTransLeaseCycle())));
        }*/
        return TableDataInfo.build(data);
    }

    @Override
    public Long selectTenantCount() {
        return vehicleTenantMapper.selectCount(null);
    }

    @Override
    public List<Integer> selectVehicleCountMonth() {
        return vehicleTenantMapper.selectVehicleCountMonth();
    }

    @Override
    public void insertOrUpdate(VehicleTenant para) {
        if (StringUtil.isBlank(para.getId())){
            para.setId(IdUtil.getSnowflakeNextIdStr());
            vehicleTenantMapper.insert(para);
        }else {
            VehicleTenant vehicleTenant = new VehicleTenant();
            vehicleTenant.setId(para.getId());
            vehicleTenant.setPhoneNumber(para.getPhoneNumber());
            vehicleTenant.setLeaseCycle(para.getLeaseCycle());
            vehicleTenant.setLeaseEndTime(para.getLeaseEndTime());
            vehicleTenantMapper.updateById(vehicleTenant);
        }
    }

    @Override
    public void exportTenantList(QueryTenant para, HttpServletResponse response) throws IOException {
        Locale locale = LocaleContextHolder.getLocale();
        String fileName = "table.tenantName";
        String message = messageSource.getMessage(fileName, null, fileName, locale);
        Map<String, String> map = translateFields(locale);
        ExcelWriter bigWriter = ExcelUtil.getBigWriter();
        List<VehicleTenant> vehicleTenants = vehicleTenantMapper.selectAllTenantList(para);
        if (vehicleTenants.size()>0){
            vehicleTenants.stream().forEach(a -> a.setTransLeaseCycle(LeaseCycleEnum.getInstance(a.getTransLeaseCycle())));
        }
        bigWriter.setColumnWidth(0, 20);
        bigWriter.setColumnWidth(1, 20);
        bigWriter.setColumnWidth(2, 20);
        bigWriter.setColumnWidth(3, 20);
        bigWriter.setColumnWidth(4, 20);
        bigWriter.setColumnWidth(5, 20);
        bigWriter.addHeaderAlias("vin", map.get("vin"));
        bigWriter.addHeaderAlias("carOwner", map.get("carOwner"));
        bigWriter.addHeaderAlias("phoneNumber",map.get("phoneNumber"));
        bigWriter.addHeaderAlias("leaseStartTime", map.get("leaseStartTime"));
        bigWriter.addHeaderAlias("leaseEndTime", map.get("leaseEndTime"));
        bigWriter.addHeaderAlias("transLeaseCycle", map.get("leaseCycle"));
        bigWriter.setOnlyAlias(true);
        CellStyle headCellStyle = bigWriter.getHeadCellStyle();
        headCellStyle.setFillBackgroundColor((short) 22);
        bigWriter.write(vehicleTenants);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(message+".xlsx", "UTF8"));
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        try {
            Workbook workbook = bigWriter.getWorkbook();
            ServletOutputStream out=response.getOutputStream();
            workbook.write(out);
            workbook.close();
            out.close();
            bigWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Map<String,String> translateFields(Locale locale){
        Map<String,String> map = new HashMap<>();
        String vin = "table.field.vin";
        String carOwner = "table.field.rental";
        String phoneNumber = "table.field.phoneNumber";
        String leaseStartTime = "table.field.leaseStartTime";
        String leaseEndTime = "table.field.leaseEndTime";
        String leaseCycle = "table.field.leaseCycle";

        map.put("vin",messageSource.getMessage(vin, null, vin, locale));
        map.put("carOwner",messageSource.getMessage(carOwner, null, carOwner, locale));
        map.put("phoneNumber",messageSource.getMessage(phoneNumber, null, phoneNumber, locale));
        map.put("leaseStartTime",messageSource.getMessage(leaseStartTime, null, leaseStartTime, locale));
        map.put("leaseEndTime",messageSource.getMessage(leaseEndTime, null, leaseEndTime, locale));
        map.put("leaseCycle",messageSource.getMessage(leaseCycle, null, leaseCycle, locale));
        return map;
    }
}
